<template>
  <div class="box">
    <div id="leftMenu">
      <div
        v-for="(node, _index) in DataNodeTypes"
        :key="_index"
        class="node node-template"
        :node-index="_index"
        draggable="true"
        @dragstart="drag"
      >
        {{ node.name }}
      </div>
    </div>
    <div
      id="diagramContainer"
      @drop="drop($event)"
      @dragover="allowDrop"
    >
      <div
        v-for="(nodeInstance, _index) in nodeInstances"
        :id="nodeInstance.id"
        :key="nodeInstance.id"
        class="node node-instance"
      >
        {{ nodeInstance.name }}
        <span
          class="node-instance-remove"
          @click="nodeInstances.splice(_index, 1)"
        >x</span>
      </div>
    </div>
  </div>
</template>

<script>
import { jsPlumb } from 'jsplumb'
import DataNodeTypes from "./DataNodeTypes";
export default {
  data() {
    return {
      DataNodeTypes,
      nodeInstances: [
        { id: '123', name: '节点名称', type: 'type1', coordinate: { layoutX: 100, layoutY: 200 } }
      ]
    }
  },
  mounted() {
    this.initDraggables()
  },
  methods: {
    initDraggables() {
      let _this = this
      jsPlumb.ready(function () {
        jsPlumb.connect({
          source: 'item_left',
          target: 'item_right',
          endpoint: 'Dot' // 	端点类型，形状
        })
        _this.nodeInstances.forEach(nodeInstance => {
          jsPlumb.draggable(nodeInstance.id)
        })
      })
    },
    drag (ev) { // 拖放触发事件
      ev.dataTransfer.setData('Text', ev.target.getAttribute('node-index'))
    },
    drop (ev) {
      ev.preventDefault()
      const examplesData = ev.dataTransfer.getData('Text')
      const nodeTemplate = this.DataNodeTypes[parseInt(data)]
      this.nodeInstances.push({ id: `node-${data}`, name: nodeTemplate.name, type: nodeTemplate.type, coordinate: { layoutX: 100, layoutY: 200 } })
      this.$nextTick(() => {
        jsPlumb.draggable(`node-${data}`)
      })
    },
    allowDrop (ev) {
      ev.preventDefault()
    },
  }
}
</script>

<style scoped>
.box {
  width: 100%;
  height: 1000px;
  overflow: hidden;
}
.node {
  width: 100px;
  height: 50px;
  border: 1px solid red;
}
.node-template {
  margin-bottom: 10px;
}
#leftMenu {
  width: 10%;
  height: 100%;
  float: left;
}
#diagramContainer {
  position: relative;
  width: 80%;
  height: 100%;
  float: right;
  border: red 1px solid;
}
.node-instance {
  position: absolute;
}
.node-instance-remove {
  position: absolute;
  right: 6px;
  top: 3px;
}
</style>
